import {
	loadModules
} from 'esri-loader';
import store from '@/store/index.js'
import toast from '../uni_modules/uview-ui/libs/config/props/toast';
import config from "@/config.js"
import {
	getFeatureLayerUrl,
	getCategory,
	getServiceCode,
	getNewPlots,
	getShowPolygonObjectid,
	getAreaBorderCode
} from "@/api/land.js"



export let city = '';
export let query = "";
export let Tools = {
	url: '', //图层地址
	map: null, //Map对象
	view: null, //MapView对象
	click_includesLayer: [], //图层点击事件所监听的图层
	znxd_tempGraphs: [], //智能选地临时绘制图形
	znxd_list: [], //智能选地结果列表
	temp_click_geo: null, //临时点击的地块
	temp_draw_feature_layer: null, //临时绘制feature图层
	temp_draw_categray_layer: null, //点击分类时临时绘制的feature图层
	temp_detail_layer: null, //详情页临时绘制的FeatureLayer
	originFeatureLayer: null, //初始化图层
	pictureSymbolLayer: null, //图片符号化图层
	tempAreaGraphics: [], //智能选地-行政区单次搜索绘制出的行政区边界图层
}

const options = {
	url: 'https://js.arcgis.com/4.27/init.js',
	css: 'https://js.arcgis.com/4.27/esri/themes/light/main.css'
};

// import Map from "@arcgis/core/Map.js";
// import MapView from "@arcgis/core/views/MapView.js";
// import FeatureLayer from "@arcgis/core/layers/FeatureLayer.js";
// import Query from "@arcgis/core/rest/support/Query.js";
// import Basemap from "@arcgis/core/Basemap.js";
// import WebTileLayer from "@arcgis/core/layers/WebTileLayer.js";
// import TileLayer from "@arcgis/core/layers/TileLayer.js";
// import MapImageLayer from "@arcgis/core/layers/MapImageLayer.js";
// import Draw from "@arcgis/core/views/draw/Draw.js";
// import Circle from "@arcgis/core/geometry/Circle.js";
// import Graphic from "@arcgis/core/Graphic.js";
// import Legend from "@arcgis/core/widgets/Legend.js";
// import Compass from "@arcgis/core/widgets/Compass.js";

// 工业用地图标
import gySvg from "@/static/position/工业.png"
// 居住用地图标
import jzSvg from "@/static/position/居住.png"
// 居住用地图标
import qtSvg from "@/static/position/其他.png"
// 商服用地图标
import sfSvg from "@/static/position/商服.png"

// 页面缩小时的图标设置
const basemaplayer_icon_renderer = {
	type: "unique-value", // autocasts as new SimpleRenderer()
	field: "ytfl",
	uniqueValueInfos: [{
			value: "工业",
			lavel: "工业",
			symbol: {
				type: "picture-marker",
				url: gySvg,
				// width: "10px",
				// height: "15px",
			}
		},
		{
			value: "居住",
			lavel: "居住",
			symbol: {
				type: "picture-marker",
				url: jzSvg,
				// width: "10px",
				// height: "15px",
			}
		},
		{
			value: "商服",
			lavel: "商服",
			symbol: {
				type: "picture-marker",
				url: sfSvg,
				// width: "10px",
				// height: "15px",
			}
		},
		{
			value: "其它",
			lavel: "其它",
			symbol: {
				type: "picture-marker",
				url: qtSvg,
				// width: "10px",
				// height: "15px",
			}
		}
	]
}


// loadModules([
// 		"esri/Map",
// 		"esri/views/MapView",
// 		"esri/layers/FeatureLayer",
// 		"esri/rest/support/Query",
// 		"esri/Basemap",
// 		"esri/layers/WebTileLayer",
// 		"esri/layers/TileLayer",
// 		"esri/layers/MapImageLayer",
// 		"esri/views/draw/Draw",
// 		"esri/geometry/Circle",
// 		"esri/Graphic",
// 	], options)
// 	.then(([Map,
// 		MapView,
// 		FeatureLayer,
// 		Query,
// 		Basemap,
// 		WebTileLayer,
// 		TileLayer,
// 		MapImageLayer,
// 		Draw,
// 		Circle,
// 		Graphic,
// 	]) => {

// 	})


/**
 * 绘制行政区边线：当前行政区（多个）为黄色边线，其余为深灰色边浅灰色面
 * @param {Object} params
 */
export const drawAreaBorder = (params) => {
	//清除上次搜索绘制的行政区图层
	Tools.view.graphics.removeMany(Tools.tempAreaGraphics)
	Tools.tempAreaGraphics = []

	//获取边界线编码，用于进一步获取区界线图层查询的url
	getAreaBorderCode().then(res => {
		let qjxCode = res.msg
		//获取区界线地址
		getFeatureLayerUrl(qjxCode).then(async layerInfo => {
			let qjxUrl = layerInfo.data[0].queryUrl

			//绘制区界线
			loadModules(
					[
						"esri/layers/FeatureLayer",
						"esri/Graphic"
					], options)
				.then(async ([
					FeatureLayer,
					Graphic
				]) => {
					//需要先查出所有行政区
					let choosedAreaSymbol = {
						type: "simple-fill",
						style: "solid",
						color: [255, 255, 255, 0],
						outline: {
							color: [66, 165, 245, 1],
							width: 2,
						},
					}
					let unselectedAreaSymbol = {
						type: "simple-fill",
						style: "solid",
						color: [220, 220, 220, 0.8],
						outline: {
							color: [66, 165, 245, 1],
							width: 2,
						},
					}
					let basemaplayer = new FeatureLayer({
						url: qjxUrl,
						title: 'qjxFeature',
						outFields: ["*"],
					});
					basemaplayer.queryFeatures({
						where: '1=1',
						outFields: ["*"],
						returnGeometry: true
					}).then(results => {
						results.features.forEach(item => {
							let tempGraphic = null
							//被勾选的行政区只画线；如果没勾选行政区，则绘制所有行政区边线（不带面）
							if (!params.params.xzq || params.params.xzq
								.indexOf(item.attributes
									.name) != -1) {
								// if (1==2) {
								tempGraphic = new Graphic({
									geometry: item.geometry,
									symbol: choosedAreaSymbol,
								});
							} else { //勾选过行政区时，没被勾选的行政区用蒙层
								tempGraphic = new Graphic({
									geometry: item.geometry,
									symbol: unselectedAreaSymbol,
								});
							}
							Tools.tempAreaGraphics.push(tempGraphic)
						})
						Tools.view.graphics.addMany(Tools.tempAreaGraphics)
					})
				})

		})

	})
}
export const initMap = (url) => {
	return new Promise((resolve, reject) => {
		loadModules(
				[
					"esri/Map",
					"esri/views/MapView",
					"esri/layers/FeatureLayer",
					"esri/rest/support/Query",
					"esri/Basemap",
					"esri/layers/WebTileLayer",
					"esri/layers/TileLayer",
					"esri/layers/MapImageLayer",
					"esri/Graphic",
					"esri/config"
				], options)
			.then(async ([Map,
				MapView,
				FeatureLayer,
				Query,
				Basemap,
				WebTileLayer,
				TileLayer,
				MapImageLayer,
				Graphic,
				esriConfig
			]) => {
				esriConfig.fontsUrl = config.appParams.mapParams.arcgisFontsUrl
				Tools.url = url
				let tiandituBaseUrl = "http://{subDomain}.tianditu.gov.cn";
				let token = "7b79e37115f10c512f76cdecda599902";

				//获取可以展示的图斑objectid
				const ShowPolygonObjectids = await getShowPolygonObjectid()
				let queryWhere = ''
				let canShowObjectids = ''
				ShowPolygonObjectids.data.forEach(item => {
					canShowObjectids += ',' + item.glGisid
				})
				if (!ShowPolygonObjectids.data.length) {
					queryWhere = '1=2'
				} else if (canShowObjectids) {
					queryWhere = ' objectid in (' +
						canShowObjectids.replace(',', '') + ')'
				} else {
					queryWhere = '1=1'
				}

				query = Query;
				//影像地图
				let tiledLayer = new WebTileLayer({
					urlTemplate: tiandituBaseUrl +
						"/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={col}&TILEROW={row}&TILEMATRIX={level}&tk=" +
						token,
					subDomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
					//spatialReference: { wkid: 4490  },
					title: "天地图影像地图",
					visible: true
				});

				//影像注记
				let tiledLayerAnno = new WebTileLayer({
					urlTemplate: tiandituBaseUrl +
						"/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={col}&TILEROW={row}&TILEMATRIX={level}&tk=" +
						token,
					subDomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
					//spatialReference: { wkid: 4490  },
					title: "天地图影像注记",
					visible: true
				});

				//矢量地图
				let vecLayer = new WebTileLayer({
					urlTemplate: tiandituBaseUrl +
						"/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={col}&TILEROW={row}&TILEMATRIX={level}&tk=" +
						token,
					subDomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
					//spatialReference: { wkid: 4490  },
					title: "天地图矢量地图",
					visible: false
				});

				//矢量注记
				let vecLayerAnno = new WebTileLayer({
					urlTemplate: tiandituBaseUrl +
						"/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={col}&TILEROW={row}&TILEMATRIX={level}&tk=" +
						token,
					subDomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
					//spatialReference: { wkid: 4490  },
					title: "天地图矢量注记",
					visible: false
				});
				//定位到市中心
				let cityCenter = [125.34, 43.88];
				// let condition = '1=1'
				// if(ghyt){
				// 	condition = "ghyt='"+ghyt+"'"
				// }
				let basemaplayer = new FeatureLayer({
					url,
					title: 'myFeature',
					outFields: ["*"],
					definitionExpression: queryWhere,
					visible: true,
					opacity: 0.6
				});
				let basemaplayer_icon = new FeatureLayer({
					url,
					title: 'myFeature',
					outFields: ["*"],
					definitionExpression: queryWhere,
					visible: true,
					renderer: basemaplayer_icon_renderer
				});
				Tools.originFeatureLayer = basemaplayer
				Tools.pictureSymbolLayer = basemaplayer_icon
				Tools.map = new Map({
					basemap: {
						baseLayers: [tiledLayer, tiledLayerAnno, vecLayer,
							vecLayerAnno
						]
					},
					layers: [basemaplayer_icon]
				});
				Tools.view = new MapView({
					container: "myMapView",
					center: cityCenter,
					zoom: config.appParams.mapParams.defaultZoom,
					map: Tools.map,
					constraints: {
						maxZoom: 18,
						// 禁止旋转
						rotationEnabled: false
					},
				});
				// Tools.view.navigation.gamepad.enabled = true

				// if (store.state.user.route != "pages/Land/details") {
				// 	let legend = new Legend({
				// 		view: Tools.view
				// 	});
				// 	Tools.view.ui.add(legend, "bottom-right");
				// 	Tools.view.ui.height = 50
				// 	Tools.view.ui.padding = {
				// 		// top: 100,
				// 		left: 200,
				// 		right: 25,
				// 		bottom: 60
				// 	}
				// 	Tools.view.ui.width = 10
				// }


				// Tools.view.ui.remove('zoom')

				city = basemaplayer_icon;
				Tools.click_includesLayer.push(Tools.originFeatureLayer)
				Tools.click_includesLayer.push(Tools.pictureSymbolLayer)
				//Tools.view.graphics.removeAll();
				Tools.view.on("click", function(event) {
					Tools.view.hitTest(event, {
						include: Tools.click_includesLayer
					}).then(function(response) {
						console.log(response)
						if (!response) return
						const feature = response.results[0]?.graphic;
						store.state.user.attributes = feature?.attributes
						store.state.user.speckleData = feature?.attributes
						let tempFeature = new Graphic({
							geometry: feature?.geometry,
							symbol: {
								type: "simple-fill",
								style: "solid",
								color: [255, 255, 255, 0],
								outline: {
									color: [0, 255, 0, 1],
									width: 2,
								},
							},
						});
						Tools.view.goTo({
							target: tempFeature,
						})
						// console.log(store.state.user.route, "ss")
						// if (store.state.user.route == "pages/Land/details" &&
						// 	feature)
						// 	return uni
						// 		.redirectTo({
						// 			url: '/pages/Land/details?objectid=' +
						// 				feature
						// 				.attributes
						// 				.objectid
						// 		})
						// if (feature) uni.navigateTo({
						// 	url: '/pages/Land/details?objectid=' + feature
						// 		.attributes
						// 		.objectid
						// })

					})
				})



				Tools.view.watch('zoom', zoomVal => {
					// console.log(zoomVal)
					if (zoomVal > config.appParams.mapParams.judgeZoom) {
						Tools.map.remove(city)
						city = Tools.originFeatureLayer
						Tools.map.add(city)
					} else {
						Tools.map.remove(city)
						city = Tools.pictureSymbolLayer
						Tools.map.add(city)
					}
					city.on("layerview-create", function(event) {
						// The LayerView for the layer that emitted this event
						setTimeout(function() {
							uni.hideLoading()
						}, 1500)
						console.log('9999999999999999999999999999')
					});
				})
				resolve()
			})
	})


};


/**
 * @param {Object} params 对象内容如增加请及时补充
 * 	{
 *  sql:sql条件
 *}
 */
export function featureLayerRefresh(params) {
	// Tools.map.removeAll()
	// loadModules(
	// 		[
	// 			"esri/layers/FeatureLayer",
	// 		], options)
	// 	.then(([
	// 		FeatureLayer,
	// 	]) => {
	// 		console.log(params.sql)
	// 		let basemaplayer = new FeatureLayer({
	// 			url: Tools.url,
	// 			title: 'myFeature',
	// 			outFields: ["*"],
	// 			definitionExpression: params.sql,
	// 			visible: true,
	// 			opacity: 0.6
	// 		});
	// 		let basemaplayer_icon = new FeatureLayer({
	// 			url: Tools.url,
	// 			title: 'myFeature',
	// 			outFields: ["*"],
	// 			definitionExpression: params.sql,
	// 			visible: true,
	// 			renderer: basemaplayer_icon_renderer
	// 		});
	// 		Tools.originFeatureLayer = basemaplayer
	// 		Tools.pictureSymbolLayer = basemaplayer_icon
	// 		Tools.click_includesLayer = []
	// 		Tools.click_includesLayer.push(Tools.originFeatureLayer)
	// 		Tools.click_includesLayer.push(Tools.pictureSymbolLayer)

	// 		if (Tools.view.zoom > config.appParams.mapParams.judgeZoom) {
	// 			city = Tools.originFeatureLayer
	// 			Tools.map.add(city)
	// 		} else {
	// 			city = Tools.pictureSymbolLayer
	// 			Tools.map.add(city)
	// 		}
	// 		// Tools.view.on("click", function(event) {
	// 		// 	Tools.view.hitTest(event, {
	// 		// 		include: Tools.click_includesLayer
	// 		// 	}).then(function(response) {
	// 		// 		debugger
	// 		// 		console.log(response)
	// 		// 		if (!response) return
	// 		// 		const feature = response.results[0]?.graphic;
	// 		// 		store.state.user.attributes = feature?.attributes
	// 		// 		let tempFeature = new Graphic({
	// 		// 			geometry: feature?.geometry,
	// 		// 			symbol: {
	// 		// 				type: "simple-fill",
	// 		// 				style: "solid",
	// 		// 				color: [255, 255, 255, 0],
	// 		// 				outline: {
	// 		// 					color: [0, 255, 0, 1],
	// 		// 					width: 2,
	// 		// 				},
	// 		// 			},
	// 		// 		});
	// 		// 		Tools.view.goTo({
	// 		// 			target: tempFeature,
	// 		// 		})
	// 		// 		// console.log(store.state.user.route, "ss")
	// 		// 		// if (store.state.user.route == "pages/Land/details" &&
	// 		// 		// 	feature)
	// 		// 		// 	return uni
	// 		// 		// 		.redirectTo({
	// 		// 		// 			url: '/pages/Land/details?objectid=' +
	// 		// 		// 				feature
	// 		// 		// 				.attributes
	// 		// 		// 				.objectid
	// 		// 		// 		})
	// 		// 		// if (feature) uni.navigateTo({
	// 		// 		// 	url: '/pages/Land/details?objectid=' + feature
	// 		// 		// 		.attributes
	// 		// 		// 		.objectid
	// 		// 		// })

	// 		// 	})
	// 		// })
	// 	})
}


// 底图切换方法
export const TabsBaseMaps = (type) => {
	let Baselayers = Tools.map.basemap.baseLayers.items;
	Baselayers.forEach(item => {
		if (type === 0) {
			if (item.title == "天地图影像地图" || item.title == "天地图影像注记") {
				item.visible = false;
			} else {
				item.visible = true;
			}
		} else {
			if (item.title == "天地图矢量地图" || item.title == "天地图矢量注记") {
				item.visible = false;
			} else {
				item.visible = true;
			}
		}
	})
}

/**
 * 获取图层数据
 * @param data格式:
 * 【{
	  name(字段名):,
	  value（搜索条件的值，数值型为长度为2的数组例如【13.1,341,2】判断的是大于等于0索引小于等于1索引，字符串或日期时为单个值，）:,
	  type(类型-字符串类型str,数值型num,日期型date):,
	  isEq(字符串类型时是否判断相等，true相等，false-like):
	  },
	  {
		name(字段名):,
		value（搜索条件的值，数值型为长度为2的数组例如【13.1,341,2】判断的是大于等于0索引小于等于1索引，字符串或日期时为单个值，）:,
		type(类型-字符串类型str,数值型num,日期型date):,
		isEq(字符串类型时是否判断相等，true相等，false-like):
	  }】
 */
export const GetLayersData = (data) => {
	return new Promise(async (resolve, reject) => {
		//处理查询条件
		let condition = '1=1'
		if (condition.length != 0) {
			condition = ''
			if (data !== '') {
				data.forEach(item => {
					if (item.type == 'str') {
						if (item.isEq) {
							condition += " and " + item.name + " = '" + item.value + "'"
						} else {
							condition += " and " + item.name + " like '%" + item.value +
								"%'"
						}
					} else if (item.type == 'num') {
						if (item.value[0] || item.value[0] == 0) {
							condition += "and " + item.name + " >= " + item.value[0]
						}
						if (item.value[1] || item.value[1] == 0) {
							condition += "and " + item.name + " <= " + item.value[1]
						}
					} else if (item.type == 'date') {
						// condition += "and " + item.name 
					} else if (item.type == 'objectid') {
						//TODO 待完成
						condition += "and " + item.name + " = " + item.value
					}
				})
			}
		}
		let query = city.createQuery()
		query.where = condition.replace("and", "")
		query.returnGeometry = true
		query.outFields = ["*"]

		//获取可以展示的图斑objectid
		const ShowPolygonObjectids = await getShowPolygonObjectid()
		let queryWhere = ''
		let canShowObjectids = ''
		ShowPolygonObjectids.data.forEach(item => {
			canShowObjectids += ',' + item.glGisid
		})
		if (!ShowPolygonObjectids.data.length) {
			query.where = '1=2'
		} else {
			if (query.where) {
				query.where += ' and objectid in (' + canShowObjectids.replace(',', '') + ')'
			} else {
				query.where = ' objectid in (' + canShowObjectids.replace(',', '') + ')'
			}
		}

		//TODO 需要同步处理
		let result = await getGraphData_sync(query);
		resolve(result)
	})
}

/**
 * 同步获取图形数据
 */
function getGraphData_sync(query) {
	return new Promise((resolve, reject) => {
		let resultData = []
		city.queryFeatures(query).then((result) => {
			result.features.forEach(item => {
				let result_ = {}
				result_ = item.attributes
				result_.patternSpotGeo = item.geometry
				resultData.push(result_)
			})
			resolve(resultData)
		})
		//Tools.view.graphics.removeAll() 
	})
}

// 根据已有图形绘制图斑
export const drawPattrenSport = (geo) => {
	loadModules([
			"esri/Graphic",
			"esri/layers/FeatureLayer",
		], options)
		.then(async ([
			Graphic,
			FeatureLayer,
		]) => {
			console.log(geo)
			// city.opacity = 0
			city.visible = false

			uni.showLoading({
				title: '地块查询中',
				mask: true
			});


			// Tools.view.graphics.removeAll()
			// if(Tools.temp_draw_feature_layer){
			// 	Tools.map.remove(Tools.temp_draw_feature_layer)
			// 	Tools.temp_draw_feature_layer = null
			// }
			// Tools.znxd_tempGraphs = []
			if (Tools.temp_click_geo) {
				Tools.view.graphics.remove(Tools.temp_click_geo)
			}
			Tools.temp_click_geo = geo
			let tempFeature = new Graphic({
				geometry: geo,
				symbol: {
					type: "simple-fill",
					style: "solid",
					color: [241, 165, 50, .5],
					outline: {
						color: [227, 5, 26, 1],
						width: 1,
					},
				},
			});
			let condition = '1=1'
			if (store.state.user.landParams && store.state.user.landParams.sql) {
				condition = store.state.user.landParams.sql
			}
			if (store.state.user.detailsParams && store.state.user.detailsParams.sql) {
				condition = store.state.user.detailsParams.sql
			}
			if (store.state.user.params && store.state.user.params.sql) {
				condition = store.state.user.params.sql
			}

			//获取可以展示的图斑objectid
			const ShowPolygonObjectids = await getShowPolygonObjectid()
			let queryWhere = ''
			let canShowObjectids = ''
			ShowPolygonObjectids.data.forEach(item => {
				canShowObjectids += ',' + item.glGisid
			})
			if (!ShowPolygonObjectids.data.length) {
				queryWhere = '1=2'
			} else if (canShowObjectids) {
				queryWhere = ' objectid in (' +
					canShowObjectids.replace(',', '') + ')'
			} else {
				queryWhere = '1=1'
			}

			condition += ' and ' + queryWhere
			console.log(condition)
			let allLayer = new FeatureLayer({
				url: Tools.url,
				title: 'myFeature',
				outFields: ["*"],
				definitionExpression: condition,
				visible: true,
				opacity: 0.6
			})



			let basemaplayer_icon = new FeatureLayer({
				url: Tools.url,
				title: 'myFeature',
				outFields: ["*"],
				definitionExpression: condition,
				visible: true,
				renderer: basemaplayer_icon_renderer
			});




			Tools.originFeatureLayer = allLayer
			Tools.pictureSymbolLayer = basemaplayer_icon

			console.log(Tools.view.zoom, '级别')

			if (Tools.temp_detail_layer) {
				Tools.map.remove(Tools.temp_detail_layer)
				Tools.temp_detail_layer = null
			}
			Tools.map.add(allLayer)



			Tools.temp_detail_layer = allLayer

			Tools.click_includesLayer.push(allLayer)
			Tools.click_includesLayer.push(basemaplayer_icon)


			// let tempInterval = setInterval(function() {
			// 	console.log(allLayer.isFulfilled())
			// 	if (allLayer.isFulfilled()) {
			// 		uni.hideLoading()
			// 		clearInterval(tempInterval)

			// 	}
			// }, 100)

			Tools.view.when(() => {
				// uni.hideLoading()
				Tools.view.goTo({
					target: tempFeature,
				})
			})
		})
}

//筛选属性地块

export const fillFeatulayer = (name) => {
	if (name == "全部") {
		city.definitionExpression = "1=1";
	} else {
		city.definitionExpression = "ghyt='" + name + "'";
	}
}
// 条件搜索与绘制
let continueSearch = true //是否需要继续查询
export const searchAndDraw = async (params) => {
	// if (params.featureType && params.featureType == 'tdtj' && store.state.user.landParams.sql == params.sql)
	// 	return
	// city.opacity = 0
	if (params.featureType && params.featureType == 'znxd') { //如果当前页面为智能选地，则绘制行政区边线：当前行政区（多个）为黄色边线，其余为深灰色边浅灰色面
		// drawAreaBorder(params)
	}
	city.visible = false;
	Tools.view.graphics.removeAll()
	if (params.isZnxdSearch) {
		Tools.view.graphics.addMany(Tools.tempAreaGraphics)
	}
	if (Tools.temp_draw_feature_layer) {
		Tools.map.remove(Tools.temp_draw_feature_layer)
		Tools.temp_draw_feature_layer = null
	}
	if (Tools.temp_draw_categray_layer) {
		Tools.map.remove(Tools.temp_draw_categray_layer)
		Tools.temp_draw_categray_layer = null
	}
	Tools.znxd_tempGraphs = []
	let results = []
	continueSearch = true
	if (!params.sql || params.sql == ' 1=1 ') {
		//查询全部时
		// city.opacity = 1
		city.visible = true;
		Tools.view.graphics.removeAll()

		// return
	}
	let needRemoveIds = ''

	let query = city.createQuery()
	query.where = params.sql

	//获取可以展示的图斑objectid
	const ShowPolygonObjectids = await getShowPolygonObjectid()
	let queryWhere = ''
	let canShowObjectids = ''
	ShowPolygonObjectids.data.forEach(item => {
		canShowObjectids += ',' + item.glGisid
	})
	if (!ShowPolygonObjectids.data.length) {
		query.where = '1=2'
	} else {
		if (query.where) {
			query.where += ' and objectid in (' + canShowObjectids.replace(',', '') + ')'
		} else {
			query.where = ' objectid in (' + canShowObjectids.replace(',', '') + ')'
		}
	}
	console.log(query)
	while (continueSearch) {
		await handleArcgisLimit(query, params.sql, needRemoveIds, results)
	}
	if (params.sql != ' 1=1 ') {
		// console.log(Tools.znxd_tempGraphs)
		Tools.view.goTo(Tools.znxd_tempGraphs)
	}

	return results
}

function handleArcgisLimit(query, sql, needRemoveIds, results) {
	return new Promise((resolve, reject) => {
		loadModules([
				"esri/Map",
				"esri/views/MapView",
				"esri/layers/FeatureLayer",
				"esri/rest/support/Query",
				"esri/Basemap",
				"esri/layers/WebTileLayer",
				"esri/layers/TileLayer",
				"esri/layers/MapImageLayer",
				"esri/views/draw/Draw",
				"esri/geometry/Circle",
				"esri/Graphic",
			], options)
			.then(([Map,
				MapView,
				FeatureLayer,
				Query,
				Basemap,
				WebTileLayer,
				TileLayer,
				MapImageLayer,
				Draw,
				Circle,
				Graphic,
			]) => {
				if (needRemoveIds) {
					if (needRemoveIds.startwith(",")) needRemoveIds = needRemoveIds.replace(",", "")
					query.where += ' and objectid not in (' + needRemoveIds + ')'
				}
				query.returnGeometry = true
				query.outFields = ["bgdz", "bianhao", "bz", "gdfs", "gdsj", "ghyt", "jcss",
					"jdqk", "jzmd", "jzxg", "ldl", "mianji", "name", "objectid", "qjdz", "quyu",
					"rjl",
					"sizhi",
				]

				//query.outFields = ["*"];
				city.queryFeatures(query).then(result => {
					if (!result.exceededTransferLimit) continueSearch = false
					if (result.features == '') {
						//city.opacity = 1;
						// city.visible = true;
					} else {
						//city.opacity = 0
						// city.visible = false;
						console.log(result, '')
						result.features.forEach(item => {
							needRemoveIds += "," + item.attributes.objectid
							let tempFeature = new Graphic({
								geometry: item.geometry,
								symbol: {
									type: "simple-fill",
									style: "solid",
									color: [255, 255, 255, 0],
									outline: {
										color: [0, 255, 0, 1],
										width: 2,
									},
								},
							});
							Tools.znxd_tempGraphs.push(tempFeature)
							results.push(item.attributes)
						})
						// Tools.view.graphics.addMany(Tools.znxd_tempGraphs);
					}

					resolve()
				})

				let tempLayer = new FeatureLayer({
					url: Tools.url,
					title: 'myFeature',
					outFields: ["*"],
					definitionExpression: query.where,
					opacity: 0.6
				});


				let basemaplayer_icon = new FeatureLayer({
					url: Tools.url,
					title: 'myFeature',
					outFields: ["*"],
					definitionExpression: query.where,
					renderer: basemaplayer_icon_renderer
				});


				console.log(Tools.view.zoom, '级别')

				// if (Tools.view.zoom > 13) {
				// Tools.originFeatureLayer = tempLayer
				// Tools.pictureSymbolLayer = basemaplayer_icon
				// 	Tools.temp_draw_categray_layer = tempLayer
				// 	Tools.map.add(tempLayer)
				// 	Tools.click_includesLayer.push(tempLayer)
				// 	return
				// }

				// Tools.temp_draw_categray_layer = basemaplayer_icon
				// Tools.map.add(basemaplayer_icon)
				// Tools.click_includesLayer.push(basemaplayer_icon)
				// Tools.originFeatureLayer = tempLayer
				// Tools.pictureSymbolLayer = basemaplayer_icon

				// Tools.temp_draw_categray_layer = tempLayer
				// Tools.map.add(tempLayer)
				// Tools.click_includesLayer.push(tempLayer)

				Tools.originFeatureLayer = tempLayer
				Tools.pictureSymbolLayer = basemaplayer_icon
				Tools.click_includesLayer.push(basemaplayer_icon)
				Tools.click_includesLayer.push(tempLayer)

				if (Tools.view.zoom > 13) {
					Tools.temp_draw_categray_layer = tempLayer
					Tools.map.add(tempLayer)
				} else {
					Tools.temp_draw_categray_layer = basemaplayer_icon
					Tools.map.add(basemaplayer_icon)
				}







				//if (params && params.sql != ' 1=1 ') {
				// console.log(Tools.znxd_tempGraphs)
				// Tools.view.goTo(tempLayer)
				//}
			})
	})
}

//清空
export const clearViewMap = () => {
	Tools.view.graphics.removeAll()
}



export const jumpPatternSpot = (geo) => {
	loadModules([
		"esri/Graphic",
		"esri/layers/FeatureLayer",
	], options).then(([Graphic, FeatureLayer]) => {
		let tempFeature = new Graphic({
			geometry: geo,
			symbol: {
				type: "simple-fill",
				style: "solid",
				color: [241, 165, 50, .5],
				outline: {
					color: [227, 5, 26, 1],
					width: 1,
				},
			},
		});
		console.log(Tools.view, 'view对象')


		Tools.view.when(function() {
			Tools.view.goTo(tempFeature)
		})

	})
}